import 'dart:convert';

import 'package:atlas/constant/color_constant.dart';
import 'package:atlas/constant/screen_constant.dart';
import 'package:atlas/screen/video_player.dart';
import 'package:atlas/service/HttpService.dart';
import 'package:banner_carousel/banner_carousel.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_svg/svg.dart';
import 'package:glass_kit/glass_kit.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:http/http.dart';
import 'package:lottie/lottie.dart';
import 'package:material_dialogs/dialogs.dart';
import 'package:material_dialogs/widgets/buttons/icon_button.dart';

import '../config/apiConfig.dart';
import '../model/FilmModel.dart';
import '../util/ApiUri.dart';
import '../widget/banner_images.dart';

class AltasHome extends StatefulWidget {
  const AltasHome({Key? key}) : super(key: key);

  @override
  State<AltasHome> createState() => _AltasHomeState();
}

class _AltasHomeState extends State<AltasHome> {
  /* Service */
  final HttpService httpService = HttpService();

  /* 下拉加载 */
  final scrollController = ScrollController(); // 当前view状态
  final List<FilmModel> filmList = [];
  int currentPage = 0;
  bool isLoading = false;
  bool isAdmin = false;

  Future<void> _loadMoreData() async {
    //print("++前" + currentPage.toString());
    currentPage++;
    //print("++后" + currentPage.toString());
    await Future.delayed(const Duration(seconds: 3));
    final newItems = await httpService.getAllFilm(currentPage.toString());
    if (newItems != null) {
      filmList.addAll(newItems);
      setState(() {
        isLoading = true;
      });
    } else {
      setState(() {
        isLoading = false;
      });
    }
  }

  dynamic responseData;

  Future<void> getData() async {
    String filmApi = "/uyapi/file_text.php";
    /* 参数 */
    final params = {
      "keeper": ApiConfig.KEEPER_Z,
      "api": ApiConfig.APPID_Z,
      "title": "data",
    };
    Response response = await post(ApiUri().apiUri(filmApi), body: params);
    if (response.statusCode == 200) {
      responseData = json.decode(response.body);
    } else {
      throw Exception('Failed to fetch video URL');
    }
    setState(() {
      isAdmin = true;
    });
  }

  @override
  void initState() {
    super.initState();
    isAdmin = false;
    _loadMoreData();
    getData();
  }

  /*
   * 字符串截取
   */
  String Strs(String s) {
    int maxCharacters = 5; // 设置最大字数
    if (s.length > maxCharacters) {
      s = '${s.substring(0, maxCharacters)}...';
    }
    return s;
  }

  @override
  Widget build(BuildContext context) {
    /* 模式设置 SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle.light);*/
    /* 背景颜色设置 */
    SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
      statusBarColor: Colors.transparent,
    ));
    // 隐藏状态栏并全屏显示
    final screenCons = ScreenConstants(context);
    if (isAdmin) {
      return Scaffold(
        body: Column(
          children: [
            Flexible(
              child: Stack(
                children: [
                  _banner(screenCons.screenHeight, screenCons.screenWidth),
                  _appBar(),
                ],
              ),
            ),
          ],
        ),
      );
    } else {
      return Scaffold(
        body: Column(
          children: [
            Flexible(
              child: Stack(
                children: [
                  Center(
                      child: Text(
                    BannerImages.appName,
                    style: GoogleFonts.bungee(
                      textStyle: TextStyle(
                        color: ColorTween(
                          begin: const Color(0xFFED1D24),
                          end: const Color(0xFFED1F69),
                        ).lerp(0.5),
                        fontSize: 24,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ))
                ],
              ),
            ),
          ],
        ),
      );
    }
  }

  /* 顶部Bar */
  Widget _appBar() {
    return ClipRect(
      child: GlassContainer(
        height: 120,
        width: double.maxFinite,
        gradient: LinearGradient(
          colors: [
            Colors.white.withOpacity(0.1),
            Colors.white.withOpacity(0.1),
          ],
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
        ),
        borderGradient: LinearGradient(
          colors: [
            Colors.white.withOpacity(0.1),
            Colors.white.withOpacity(0.1),
            Colors.lightBlueAccent.withOpacity(0.1),
            Colors.lightBlueAccent.withOpacity(0.1)
          ],
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
          stops: const [0.0, 0.39, 0.40, 1.0],
        ),
        blur: 5,
        alignment: Alignment.center,
        child: Container(
          color: Colors.transparent,
          margin: const EdgeInsets.only(top: 40, left: 20, right: 20),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Expanded(
                child: Align(
                  alignment: Alignment.centerLeft,
                  child: Text(
                    BannerImages.appBigName,
                    style: TextStyle(
                      fontFamily: 'MainFont',
                      color: ColorTween(
                        begin: const Color(0xFFED1D24),
                        end: const Color(0xFFED1F69),
                      ).lerp(0.5),
                      fontSize: 24,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),
              ),
              Align(
                alignment: Alignment.centerRight,
                child: GestureDetector(
                  onTap: () {
                    dialog_m(context);
                  },
                  child: SvgPicture.asset(
                    'assets/svg/Search.svg',
                    height: 24,
                    width: 24,
                    color: ColorConstants.primary_red,
                  ),
                ),
              )
            ],
          ),
        ),
      ),
    );
  }

  void dialog_m(BuildContext context) {
    return Dialogs.bottomMaterialDialog(
        msg: '欢迎使用我的软件，希望这些电影对您带来快乐.\n如果你有问题可以联系我QQ:3250686270.\n祝你开心.🥳',
        title: "${BannerImages.appName}通知",
        color: Colors.white,
        lottieBuilder: Lottie.asset(
          'assets/lottie/cong_example.json',
          fit: BoxFit.contain,
        ),
        /*customView: Image.asset(
          'assets/image/group.png',
          width: double.maxFinite,
          height: 200,
        ),*/
        context: context,
        actions: [
          IconsButton(
            onPressed: () {
              Navigator.of(context).pop(['Test', 'List']);
            },
            text: '确定',
            iconData: Icons.check_circle_outline,
            color: Colors.green,
            textStyle: const TextStyle(color: Colors.white),
            iconColor: Colors.white,
          ),
        ]);
  }

  /* Banner */
  Widget _banner(double height, double width) {
    return SingleChildScrollView(
      physics: const BouncingScrollPhysics(),
      child: Column(
        children: [
          /* 导航图 */
          BannerCarousel(
            customizedIndicators: const IndicatorModel.animation(
                width: 15, height: 2, spaceBetween: 3, widthAnimation: 50),
            height: height * 0.7,
            borderRadius: 0,
            margin: const EdgeInsets.all(0),
            animation: true,
            indicatorBottom: false,
            disableColor: ColorConstants.primary_grey,
            activeColor: ColorConstants.primary_red,
            customizedBanners: [
              GestureDetector(
                onTap: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                      builder: (context) => VideoPlayerM(
                          url: responseData['url1'], icon: '', title: ''),
                    ),
                  );
                },
                child: CachedNetworkImage(
                  imageUrl: responseData['img1'],
                  fit: BoxFit.cover,
                  errorWidget: (context, url, error) =>
                      Image.asset('assets/image/ic_load.png'),
                ),
              ),
              GestureDetector(
                onTap: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                      builder: (context) => VideoPlayerM(
                          url: responseData['url2'], icon: '', title: ''),
                    ),
                  );
                },
                child: CachedNetworkImage(
                  imageUrl: responseData['img2'],
                  fit: BoxFit.cover,
                  errorWidget: (context, url, error) =>
                      Image.asset('assets/image/ic_load.png'),
                ),
              ),
              GestureDetector(
                onTap: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                      builder: (context) => VideoPlayerM(
                          url: responseData['url3'], icon: '', title: ''),
                    ),
                  );
                },
                child: CachedNetworkImage(
                  imageUrl: responseData['img3'],
                  fit: BoxFit.cover,
                  errorWidget: (context, url, error) =>
                      Image.asset('assets/image/ic_load.png'),
                ),
              ),
              GestureDetector(
                onTap: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                      builder: (context) => VideoPlayerM(
                          url: responseData['url4'], icon: '', title: ''),
                    ),
                  );
                },
                child: CachedNetworkImage(
                  imageUrl: responseData['img4'],
                  fit: BoxFit.cover,
                  errorWidget: (context, url, error) =>
                      Image.asset('assets/image/ic_load.png'),
                ),
              ),
              GestureDetector(
                onTap: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                      builder: (context) => VideoPlayerM(
                          url: responseData['url5'], icon: '', title: ''),
                    ),
                  );
                },
                child: CachedNetworkImage(
                  imageUrl: responseData['img5'],
                  fit: BoxFit.cover,
                  errorWidget: (context, url, error) =>
                      Image.asset('assets/image/ic_load.png'),
                ),
              ),
            ],
          ),
          /* 分类标题 */
          Container(
            width: width,
            height: 50,
            margin: const EdgeInsets.only(right: 16, left: 16),
            alignment: Alignment.centerLeft,
            child: Text(
              'Tawsiya',
              textAlign: TextAlign.left,
              style: GoogleFonts.itim(
                textStyle: TextStyle(
                  color: ColorTween(
                    begin: const Color(0xFFED1D24),
                    end: const Color(0xFFED1F69),
                  ).lerp(0.5),
                  fontSize: 20,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
          ),
          /* 实现列表 */
          NotificationListener<ScrollNotification>(
            onNotification: (scrollNotification) {
              if (!isLoading &&
                  scrollNotification.metrics.pixels ==
                      scrollNotification.metrics.maxScrollExtent) {
                setState(() {
                  isLoading = true;
                });
                _loadMoreData();
              }
              _loadMoreData();
              return true;
            },
            child: Container(
              margin: const EdgeInsets.only(bottom: 8, left: 8, right: 8),
              child: GridView.builder(
                gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 3,
                  childAspectRatio: 0.65,
                ),
                //* 移除上方的空格 *//
                padding: EdgeInsets.zero,
                shrinkWrap: true,
                controller: scrollController,
                physics: const BouncingScrollPhysics(),
                itemCount: filmList.length > 300
                    ? filmList.length
                    : filmList.length + 1,
                itemBuilder: (BuildContext context, int index) {
                  /*print('index $index');
                  print('items.length ' + (filmList.length).toString());*/

                  if (index == filmList.length) {
                    return _buildProgressIndicator();
                  } else {
                    return GestureDetector(
                      onTap: () async {
                        String id = filmList[index].id;
                        String image = filmList[index].image;
                        String title = filmList[index].title;
                        String url = await httpService.getVideoUrl(id);
                        /*await launch(url);*/
                        Navigator.push(
                          context,
                          MaterialPageRoute(
                            builder: (context) => VideoPlayerM(
                                url: url, icon: image, title: title),
                          ),
                        );
                      },
                      child: Container(
                        margin: const EdgeInsets.symmetric(
                            horizontal: 5, vertical: 5),
                        decoration: BoxDecoration(
                          color: Colors.white,
                          borderRadius: BorderRadius.circular(16),
                          boxShadow: [
                            BoxShadow(
                              color: Colors.grey.withOpacity(0.5),
                              blurRadius: 1,
                            ),
                          ],
                        ),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            Expanded(
                              child: ClipRRect(
                                borderRadius: const BorderRadius.only(
                                  topLeft: Radius.circular(16),
                                  topRight: Radius.circular(16),
                                ),
                                child: CachedNetworkImage(
                                  imageUrl: filmList[index].image,
                                  fit: BoxFit.cover,
                                  width: 150,
                                  errorWidget: (context, url, error) =>
                                      Image.asset('assets/image/ic_load.png'),
                                ),
                              ),
                            ),
                            Padding(
                              padding: const EdgeInsets.all(8),
                              child: Column(
                                mainAxisAlignment: MainAxisAlignment.start,
                                crossAxisAlignment: CrossAxisAlignment.end,
                                children: [
                                  Text(
                                    filmList[index].title,
                                    textAlign: TextAlign.right,
                                    maxLines: 1,
                                    overflow: TextOverflow.fade,
                                    style: GoogleFonts.cairo(
                                        fontSize: 10,
                                        fontWeight: FontWeight.bold),
                                  ),
                                  Row(
                                    mainAxisAlignment: MainAxisAlignment.end,
                                    crossAxisAlignment:
                                        CrossAxisAlignment.center,
                                    children: [
                                      Container(
                                        padding: const EdgeInsets.symmetric(
                                            horizontal: 8),
                                        decoration: BoxDecoration(
                                          color: Colors.black.withOpacity(0.2),
                                          // 将背景颜色设置为半透明的黑色
                                          borderRadius: BorderRadius.circular(
                                              6), // 将边框设置为圆角
                                        ),
                                        child: Text(
                                          Strs(filmList[index].score.trim()),
                                          style: const TextStyle(
                                              fontFamily: 'MainFont',
                                              fontSize: 12,
                                              color: Colors.white),
                                          overflow: TextOverflow.ellipsis,
                                          // 添加省略号
                                          maxLines:
                                              1, // 设置最大行数为1，即限制最大字符数量// 设置文本样式
                                        ),
                                      ),
                                      const SizedBox(width: 4),
                                      const Icon(
                                        Icons.star,
                                        color: ColorConstants.primary_red,
                                        size: 16,
                                      ),
                                    ],
                                  ),
                                ],
                              ),
                            ),
                          ],
                        ),
                      ),
                    );
                  }
                },
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildProgressIndicator() {
    if (isLoading) {
      _loadMoreData();
      return const Padding(
        padding: EdgeInsets.all(8.0),
        child: SizedBox(
          width: 300,
          child: Center(
            child: Opacity(
              opacity: 1,
              child: Center(
                  child: CircularProgressIndicator(
                color: ColorConstants.primary_red,
                strokeWidth: 5,
              )),
            ),
          ),
        ),
      );
    } else {
      return Container();
    }
  }
}
